const fs = require('fs');
const Path = require('path');

const Controller = require('egg').Controller;

class MediaController extends Controller {
  // 文件上传
  async upload() {
    const ctx = this.ctx;
    const stream = await ctx.getFileStream();
    const fileName = await ctx.service.media.saveMedia(stream);
    ctx.success({
      data: fileName,
    });
  }

  async show() {
    const ctx = this.ctx;
    const {
      filename,
    } = ctx.params;
    const pathname = `${this.config.uploadDest}/${filename}`;
    if (fs.existsSync(pathname)) {
      ctx.type = `image/${Path.extname(filename)}`;
      ctx.body = fs.createReadStream(pathname);
    } else {
      ctx.body = 'no resource';
    }
  }
}


module.exports = MediaController;
